import os
from api_test.common.api_response import JsonResponse
from api_test.models import LoadFile, Project, ApiStatusCode
from api_test.serializers import ApiStatusCodeDeserializer
from fotoable_api_test import settings
from api_test.common_exception.exceptions import FileIsNoneException, FileNotFoundException
from api_test.common.decorator import catch_exception
from django.core.exceptions import ObjectDoesNotExist


def read_csv_file(file_path):
    code_list = []
    with open(file_path, 'r+') as f:
        contents = f.readlines()
    if len(contents) > 1:
        for content in contents[1:]:
            code, description = content.split(',')
            code_list.append({'code': code, 'description': description})
    else:
        raise FileIsNoneException()
    return code_list


def import_status_code(file_id, project_id):
    file_dir = os.path.join(settings.MEDIA_ROOT, 'loadfile/')
    try:
        file_load = LoadFile.objects.get(id=file_id, project_id=project_id, status=True)
        file_path = os.path.join(file_dir, file_load.file.path)
    except ObjectDoesNotExist:
        raise FileNotFoundException(file_id, project_id)
    except Exception:
        raise Exception
    return read_csv_file(file_path)


@catch_exception
def add_status_code(project_id, file_id):
    data = import_status_code(file_id, project_id)
    obj_project = Project.objects.get(id=project_id, status=True)
    name_list = [int(item.get('code')) for item in data]
    obj_api = ApiStatusCode.objects.filter(project=project_id, code__in=name_list)
    if obj_api.count() > 0:
        obj_api.delete()
    serialize = ApiStatusCodeDeserializer(data=data, many=True)
    if serialize.is_valid():
        serialize.save(project=obj_project)
    else:
        return JsonResponse(code="999998", msg="失败!")
    id_list = [obj.id for obj in ApiStatusCode.objects.filter(project_id=project_id, code__in=name_list)]
    return JsonResponse(data={
        "idList": id_list}, code="999999", msg="成功!")





